<?php

namespace App\Service\Workflow;

use App\Enums\Workflow\WorkflowV2Enum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\FeiShu\SendFs;
use App\Models\Kms\User\KmsUser;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\Workflow\WorkflowV2OrderModel;
use App\Models\WorkOrder\WorkflowV2TypeModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\System\SystemNotifyService;
use GuzzleHttp\Exception\GuzzleException;
use Ritaswc\LarkCardMessageBuilder\CardMessageBuilder;
use Ritaswc\LarkCardMessageBuilder\Tag;

class WorkflowV2OrderCCService
{
    protected WorkflowV2OrderModel $workflowV2OrderModel;
    protected array                $ccConfig;

    public function __construct($workflowV2OrderModel, array $ccConfig)
    {
        $this->workflowV2OrderModel = $workflowV2OrderModel;
        $this->ccConfig             = $ccConfig;
    }

    /**
     * @throws GuzzleException
     */
    public function handle()
    {
        if (empty($ccInfo['config'])) {
            return;
        }

        foreach ($ccInfo['config'] as $config) {
            $this->handleOneByOne($config);
        }
    }

    /**
     * @throws GuzzleException
     */
    public function handleOneByOne(array $config)
    {
        $ccType = $config['ccType'] ?? 0;
        switch ($ccType) {
            case WorkflowV2Enum::CC_TYPE_KF_USER:  // 飞书用户
                $this->sendByFeishuUser($config);
                break;
            case WorkflowV2Enum::CC_TYPE_FS_GROUP:  // 飞书群
                $this->sendByFeishuWebHock($config);
                break;
            case WorkflowV2Enum::CC_TYPE_SHOP_BOSS:  // 门店加盟商
                $this->sendByShopSignatory();
                break;
            case WorkflowV2Enum::CC_TYPE_SUBMITTER:  // 提交人
                $this->sendByShopSubmitter();
                break;
            default:
        }
    }


    /**
     * @throws GuzzleException
     */
    public function sendByFeishuUser(array $config)
    {
        // 获得飞书ID
        $feishuIds = KmsUser::query()->whereIn('rmsUserId', $config['ccUids'])->pluck('userId')->filter()->toArray();
        $cardArr  = $this->getSendFeishuCardArr();

        foreach ($feishuIds as $feishuId) {
            MessageSendService::sendMessage($feishuId, 'user_id', $cardArr, 'interactive', UserPermissionAuth::MODULE_WORK_ORDER);
        }
    }


    /**
     * @param array $config
     * @return void
     */
    public function sendByFeishuWebHock(array $config)
    {
        $cardArr = $this->getSendFeishuCardArr();
        SendFs::newRobot()
            ->coverConfig($config['webhock'], $config['secret'])
            ->setCardMessageBody($cardArr)
            ->send();
    }


    /**
     * @return void
     */
    public function sendByShopSignatory()
    {
        $this->merchantNotify();
    }

    /**
     * @param array $config
     * @return void
     */
    public function sendByShopSubmitter()
    {
        $this->merchantNotify($this->workflowV2OrderModel->createdByUid);
    }


    /**
     * 获得飞书发送的Json
     * @return array
     */
    public function getSendFeishuCardArr(): array
    {
        return WorkflowV2OrderService::getWebFsCardArr($this->workflowV2OrderModel);
    }

    /**
     * 给商家推送消息
     * @param int $userId
     * @return void
     */
    public function merchantNotify(int $userId = 0)
    {
        $url = config('webUrl.notify_web_cdn_url') . "#/pages/work-order/work-flow/progress-detail?workOrderNo={$this->workflowV2OrderModel->workflowNo}";

        $shopInfo = $this->workflowV2OrderModel->shopRel;
        $shopName = $shopInfo->shopCode . $shopInfo->name;
        $title    = "“{$this->workflowV2OrderModel->name}”工单抄送";
        $content  = "尊敬的夸父伙伴您好，您于 {$this->workflowV2OrderModel->createdAt->toDateTimeString()} 提交的“{$this->workflowV2OrderModel->name}”工单（ID：{$this->workflowV2OrderModel->workflowNo}），已处理回复相关信息，请点击查看详情。【{$shopName}】";

        // 向商家发送流程信息
        $notify = SystemNotifyService::save(
            false,
            $title,
            SystemNotifyCenterModel::NOTIFY_TYPE_2,
            $userId ? SystemNotifyCenterModel::NOTIFY_TARGET_3 : SystemNotifyCenterModel::NOTIFY_TARGET_1,
            '',
            $title,
            $url,
            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
            $content,
            $content,
            SystemNotifyCenterModel::IS_POPUP_ON,
            1,
            $this->workflowV2OrderModel->shopId,
        );
        SystemNotifyService::recordLog($notify, '创建消息');

        if ($userId) {
            SystemNotifyService::preSend($notify->id, [$userId]);
        } else {
            SystemNotifyService::send($notify->id);
        }
    }

}
